package com.yuanhang.readsms;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yuanhang.readsms.base.BaseRVAdapter;
import com.yuanhang.readsms.base.BaseRVHolder;
import com.yuanhang.readsms.bean.Sms;
import com.yuanhang.readsms.bean.SmsItem;
import com.yuanhang.readsms.databinding.ActivitySmsDetailsBinding;

import org.litepal.LitePal;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

public class SmsDetailsActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivitySmsDetailsBinding binding;
    private String phoneNumber;
    private String smsList;
    private BaseRVAdapter<SmsItem> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySmsDetailsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
        initData();
    }

    private void initView() {
        phoneNumber = getIntent().getStringExtra("phoneNumber");
        smsList = getIntent().getStringExtra("smsList");

        binding.icTitle.tvTitle.setText(phoneNumber);
        binding.icTitle.ivBack.setOnClickListener(this);
    }

    private void initData() {
        adapter = new BaseRVAdapter<SmsItem>(R.layout.item_sms_details) {
            @Override
            public void onBindVH(BaseRVHolder holder, SmsItem data, int position) {
                holder.setText(R.id.tvContent, data.getContent());
                holder.setText(R.id.tvAddTime, data.getAddTime());
            }
        };
        binding.rvDetails.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        binding.rvDetails.setAdapter(adapter);
        Type listType = new TypeToken<List<SmsItem>>() {
        }.getType();
        List<SmsItem> smsItemList = new Gson().fromJson(smsList, listType);
        Collections.reverse(smsItemList);//倒序排列
        adapter.setNewData(smsItemList);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivBack) {
            finish();
        }
    }
}